package com.app.micaihu.view.main.fragment;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.volley.VolleyError;
import com.app.config.LoadViewConfig;
import com.app.micaihu.R;
import com.app.micaihu.ad.AdConfig;
import com.app.micaihu.adapter.NewsAdapter;
import com.app.micaihu.adapter.PagerAdapter.NewsPicPagerAdapter;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseListRefreshFragment;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.ad.NativeAd;
import com.app.micaihu.bean.game.GameCenterEntity;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.bean.news.NewsList;
import com.app.micaihu.bean.news.VideoEntity;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.PairViewPager;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.IPushManager;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.utils.StatServiceUtils;
import com.app.micaihu.videoplayer.JCMediaManager;
import com.app.micaihu.videoplayer.JCVideoPlayer;
import com.app.micaihu.view.main.MainActivity;
import com.app.micaihu.view.main.topic.PostSendActivity;
import com.app.micaihu.view.newsdetail.VideoDetailActivity;
import com.app.micaihu.view.search.SearchActivity;
import com.app.utils.pulltorefresh.PullToRefreshBase;
import com.app.utils.pulltorefresh.internal.LoadingLayout;
import com.app.utils.util.GsonUtils;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;

/**
 * 新闻列表Fragment
 * Created by linkai on 2016/7/14.
 */
public class NewsFragment extends BaseListRefreshFragment<NewsEntity> implements LoadingLayout.onExtraHeaderClickListener {

    /*********
     * 逻辑数据
     **********/
    private String mChannelId;//栏目id
    private String mChannelName;//栏目名称
    private String mChannelType;//栏目类型
    private boolean isFocus;//是否是聚焦栏目
    private boolean isShowGuild;//是否执行过引导程序
    private int mMark;//下拉刷新请求标识
    int mFlushIndex = -1;//刷新下标
    int topIndex = -1;//置顶的下标
    int mFlushCount;//下拉刷新的总数量

    //已经加载过的新闻 （用于新闻去重）
    private HashMap<String, String> listHasp = new HashMap<String, String>();

    private List<NewsEntity> pisitionList;//指定位置文章列表
    //广告相关
    private List<NativeAd> adList;//广告列表
    private int circleNum;//广告间隔
    private NativeAd circleNativeAd;//加载更多循环广告
    private int installValue;//游戏是否安装的变化值(卸载或者安装此值都会变化)

    //操作监听
    private MainActivity.OnRefreshingListener mOnRefreshingListener;
    private boolean isStop;//listView是否停止
    private NewsEntity gameRanking;
    private int rankIndex;

    @Override
    public void onStart() {
        super.onStart();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMark = 0;
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        mChannelId = (args != null ? args.getString(Config.Extra.id, "0") : "0");
        mChannelName = (args != null ? args.getString(Config.Extra.name, "null") : "null");
        mChannelType = (args != null ? args.getString("type", null) : null);
        isFocus = true;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if ("推荐".equals(mChannelName)) {
            ivTopic.setVisibility(View.VISIBLE);
            ivTopic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    StatServiceUtils.event(Config.EventBauduId.square_post, "广场_发帖");

                    Intent intent = new Intent(activity, PostSendActivity.class);
                    startActivity(intent);
                    activity.overridePendingTransition(R.anim.translate_slide_in_bottom, R.anim.slide_out_left);
                }
            });
        } else {
            ivTopic.setVisibility(View.GONE);
        }
    }


    @Override
    protected void changeView() {
//        //添加头部搜索
//        ILoadingLayout iLoadingLayout = mListView.getLoadingLayoutProxy(true, false);
//        iLoadingLayout.addExtraHeader(R.layout.layout_head_search);
//        iLoadingLayout.showOrHideExtraHeader(true);
//        iLoadingLayout.setOnExtraHeaderClickListener(this);
        mListView.getRefreshableView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isScroll = true;
                return false;
            }
        });

        mListView.getRefreshableView().setOnScrollListener(new AbsListView.OnScrollListener() {

            int firstPosition = 1;//上一次的第一个位置
            int lastPosition;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (isStop && !mListView.isRefreshing()) {
                        mListView.showFootView();
                        onPullUpToRefresh(mListView);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //滚动过程中：ListView中最上面一个Item还是同一个Item
                if (isScroll && "推荐".equals(mChannelName)) {
                    if (isSameRow(firstVisibleItem)) {
                        int newScrollY = getTopItemScrollY();
                        boolean isExceedThreshold = Math.abs(mLastScrollY - newScrollY) > mScrollThreshold;
                        if (isExceedThreshold) {
                            if (mLastScrollY > newScrollY && FAB_VISIBLE == true) {
                                FAB_VISIBLE = false;
                                hideFAB();
                            } else if (mLastScrollY < newScrollY && FAB_VISIBLE == false) {
                                FAB_VISIBLE = true;
                                showFAB();
                            }
                        }
                        mLastScrollY = newScrollY;
                    } else {
                        if (firstVisibleItem > mPreviousFirstVisibleItem && FAB_VISIBLE == true) {  //向下滚动
                            FAB_VISIBLE = false;
                            hideFAB();
                        } else if (firstVisibleItem < mPreviousFirstVisibleItem && FAB_VISIBLE == false) { //向上滚动
                            FAB_VISIBLE = true;
                            showFAB();
                        }
                        mLastScrollY = getTopItemScrollY();
                        mPreviousFirstVisibleItem = firstVisibleItem;
                    }

                }

                if (JCVideoPlayer.IS_FULLSCREEN) {
                    return;
                }
                if ((totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1)) {
                    isStop = true;
                } else {
                    isStop = false;
                }
                //如果当前有视频播放则判断滑动屏幕时是否暂停视频
                if (!TextUtils.equals(mChannelType, TypeConstant.CHANNEL_TYPE_VIDEO) && JCMediaManager.isUseing) {
                    if (firstPosition < firstVisibleItem) {
                        //说明手指上滑
                        if (mAdapter != null) {
                            if (!TextUtils.isEmpty(((NewsEntity) mAdapter.getItem(firstPosition - 1)).getVideoCurl())) {
                                //如果滚出屏幕的是视频稿子则 停止播放器
                                JCVideoPlayer.releaseAllVideos();
                            }
                        }

                        firstPosition = firstVisibleItem;

                    } else if (lastPosition > (firstVisibleItem + visibleItemCount)) {
                        //说明手指下滑
                        if (!TextUtils.isEmpty(((NewsEntity) mAdapter.getItem(lastPosition - 1)).getVideoCurl())) {
                            //如果滚出屏幕的是视频稿子则 停止播放器
                            JCVideoPlayer.releaseAllVideos();
                        }
                        firstPosition = firstVisibleItem;
                    }
                    lastPosition = firstVisibleItem + visibleItemCount;
                }
            }
        });
    }

    private boolean isScroll = false;
    private boolean FAB_VISIBLE = true;
    private int mPreviousFirstVisibleItem;   //记录前面第一个Item
    private int mLastScrollY;            //记录ListView中最上面的Item(View)的上一次顶部Y坐标()
    private int mScrollThreshold = 2;   //阈值：单位px

    private boolean isSameRow(int firstVisisbleItem) {
        return mPreviousFirstVisibleItem == firstVisisbleItem;
    }

    /**
     * 滚动过程中，获得当前ListView中最上面的Item(View)的顶部的Y坐标(以px为单位)
     *
     * @return
     */
    private int getTopItemScrollY() {
        if (mListView == null || mListView.getChildAt(0) == null) return 0;
        View topChild = mListView.getChildAt(0);
        return topChild.getTop();
    }

    private boolean isAnimatorEnd;

    private void hideFAB() {
        isAnimatorEnd = false;
        ObjectAnimator animator = ObjectAnimator.ofFloat(ivTopic, "translationX", SizeUtils.dp2px(70f));
        animator.setDuration(600);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isAnimatorEnd = true;
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();


    }

    private void showFAB() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(ivTopic, "translationX", 0);
        animator.setDuration(600);
        if (!isAnimatorEnd) {
            animator.setStartDelay(1200);
        }
        animator.start();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (installValue != AppConfigTools.installValue) {
            //如果发生过安装或者卸载  则刷新列表更新下载游戏按钮的样式
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
            installValue = AppConfigTools.installValue;
        }
        notifyDown();
        try {
            if (AppConfigTools.isShowPushDialog && isFocus && getUserVisibleHint()
                    && (activity instanceof MainActivity) && (((MainActivity) activity).getMainFragmentCurrent() == 0)) {
                IPushManager.getInstance().showFoucsDialog(getActivity(), null, TypeConstant.SOURCETYPE_FOCUS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            notifyDown();
        }
        try {
            if (AppConfigTools.isShowPushDialog && isFocus && getUserVisibleHint()
                    && (activity instanceof MainActivity) && (((MainActivity) activity).getMainFragmentCurrent() == 0)) {
                IPushManager.getInstance().showFoucsDialog(getActivity(), null, TypeConstant.SOURCETYPE_FOCUS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 刷新 downview
     */
    public void notifyDown() {
//        if (DownloadUtils.DOWNLOADED != 0 && mAdapter != null) {
//            mAdapter.notifyDataSetChanged();
//        }
    }


    @Override
    protected void changeData(final boolean isRefresh) {
        HashMap<String, String> parmsMap = new HashMap<String, String>();
        parmsMap.put("type", mChannelId + "");
        parmsMap.put("page", dataPage + "");
        parmsMap.put("mark", mMark + "");
        HttpListener<DataBean<NewsList>> httpListener = new HttpListener<DataBean<NewsList>>() {

            @Override
            public void onStart() {
                setLoadView(LOADING, null);
                //改变导航栏底部图标
                if (isRefresh) {
                    //说明是手指下拉刷新
                    if (mOnRefreshingListener != null) {
                        mOnRefreshingListener.onDataRefreshingStart();
                    }
                }

            }

            @Override
            public void onError(VolleyError error) {
                if (mOnRefreshingListener != null) {
                    mOnRefreshingListener.onDataRefreshingEnd();
                }
                setLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror));
//                if (BuildConfig.LOG_DEBUG) {
////                    AppFileUtils.writeDebugFile("新闻列表","newsfragment","请求失败--"+error.getMessage(),AppConfigTools.APKFLODER + File.separator + "adfile");
//                }
            }

            @Override
            public void onSuccess(DataBean<NewsList> response) {

                if (response.noError()) {
                    NewsList newsList = response.getData();
                    if (newsList != null) {
                        //刷新广告配置
                        if (newsList.getAdConfig() != null && newsList.getAdConfig().size() > 0) {
                            //刷新广告集合
                            adList = newsList.getAdConfig();
                            //上拉广告配置
                            circleNum = newsList.getCircleNum();
                            circleNativeAd = newsList.getCircleAdConfig();
                        }
                        //配置置顶文章集合
                        if (newsList.getAdArcList() != null && newsList.getAdArcList().size() > 0) {
                            pisitionList = newsList.getAdArcList();
                        }
                        List<NewsEntity> list = newsList.getNewsList();
                        if (list != null && list.size() > 0) {
                            if (dataList == null) {
                                dataList = new ArrayList<>();
                            }
                            //数据去重
//
                            if (isRefresh) {
                                dataList.clear();
                                if (mMark == 0) {
                                    //如果mark为0 说明是初始化的刷新
                                    initHeadData(newsList.getGameCarouselList(), newsList.getVideoList(), false);//刷新头部轮播
                                    LogUtils.e(getClass().getSimpleName(), "------- "+list.size());
                                    insertAd(list);//添加广告
                                    LogUtils.e(getClass().getSimpleName(), "->  "+list.size());
                                    insertPositionNews(pisitionList, list);//添加指定位置的文章
                                    dataList.addAll(list);
                                    gameRanking = flushRankData(response);
                                    int index;
                                    //根据索引,将排行榜插入到list 中
                                    if (gameRanking != null) {
                                        if (response.getData().getRankListPosition() >= dataList.size()) {
                                            index = dataList.size() - 1;
                                        } else if (response.getData().getRankListPosition() <= 1) {
//                                            index = 1 + topIndex;
                                            index = 0;
                                        } else {
//                                            index = response.getData().getRankListPosition() + topIndex;
                                            index = response.getData().getRankListPosition() - 1;
                                        }
                                        if (index >= 0 && index < dataList.size()) {
                                            rankIndex = index;
                                        }
                                    }
                                    if (rankIndex > -1 && gameRanking != null) {
                                        //添加排行榜
                                        dataList.add(rankIndex, gameRanking);
                                    }
                                } else {
                                    //去除之前增加的刷新样式 数据
                                    if (mFlushIndex >= 0 && mFlushIndex < dataList.size()) {
                                        dataList.remove(mFlushIndex);
                                    }
                                    initHeadData(newsList.getGameCarouselList(), newsList.getVideoList(), true);//刷新头部轮播
                                    insertFlushAd(list, newsList.getRandAdConfig());//添加广告
                                    mFlushCount += list.size();//刷新下拉的广告总数
                                    //创造上一次刷新的数据
                                    NewsEntity newsFlush = new NewsEntity();
                                    newsFlush.setArticleType(TypeConstant.FLUSH + "");
                                    list.add(newsFlush);
                                    if (list.size() > 1) {
                                        //最后一个位置添加刷新数据
                                        mFlushIndex = list.size() + topIndex;
                                        try {
                                            int index = topIndex + 1 > dataList.size() ? dataList.size() : topIndex + 1;
                                            dataList.addAll(index, list);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    } else {
                                        try {
                                            int index = mFlushIndex > dataList.size() ? dataList.size() : mFlushIndex;
                                            dataList.add(index, newsFlush);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            } else {
                                dataRevisited(list, true);
                                //追加数据集合
                                insertAd(list);
                                insertPositionNews(pisitionList, list);//添加指定位置的文章
                                dataList.addAll(list);
                            }

                            if (mAdapter == null) {
//                                mAdapter = new NewsAdapter(dataList, activity, mChannelType);
                                List<GameCenterEntity> gameCenterEntityList = response.getData().getRankList();
                                String rankName = response.getData().getRankName();
                                mAdapter = new NewsAdapter(dataList, activity, mChannelType, mChannelName, gameCenterEntityList, rankName);
                                //mAdapter = new NewsAdapter(dataList, activity, mChannelType,NewsFragment1.this);
                                mListView.setAdapter(mAdapter);
                            } else {
                                try {
                                    List<GameCenterEntity> gameCenterEntityList = response.getData().getRankList();
                                    if (gameCenterEntityList != null && gameCenterEntityList.size() > 0) {
                                        ((NewsAdapter) mAdapter).setRankList(gameCenterEntityList);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                mAdapter.notifyDataSetChanged();
                            }
                            if (isRefresh) {
                                if (list.size() > 1) {
                                    if (mMark != 0) {
                                        String msg;
                                        msg = "推荐引擎有<font color='#5a9722'>" + (list.size() - 1) + "</font>条新数据";
                                        //updateLoadView(LOADSUCES, Html.fromHtml(msg));
                                        setLoadView(LOADSUCES, Html.fromHtml(msg));
                                    } else {
                                        setLoadView(LOADSUCES, "");
                                    }
                                } else {
                                    //updateLoadView(LOADSUCES, "暂无新数据");
                                    setLoadView(LOADSUCES, getString(R.string.pullup_nomore_data));
                                }
                                showFAB();
                            } else {
                                setLoadView(LOADSUCES, "");
                            }
                        } else {
                            setLoadView(LOADSUCES, getString(R.string.pullup_nomore_data));
                        }

                    } else {
                        setLoadView(DATAERROR, response.getErrorMsg());
                    }
                } else {
                    setLoadView(DATAERROR, response.getMsg());
                }
            }
        };
        if (mMark >= 1) {
            // 请求新闻列表接口
            addPostRequest(URIContant.NEWSLIST, new TypeToken<DataBean<NewsList>>() {
            }.getType(), parmsMap, httpListener);
        } else {
            addPostCacheRequest(URIContant.NEWSLIST, new TypeToken<DataBean<NewsList>>() {
            }.getType(), parmsMap, httpListener);
        }

//        if (mMark >= 1) {
//            //下拉刷新无缓存
//            if (TextUtils.equals(mChannelId, "9")) {
//                // 原创的栏目id是9 请求原创接口
//                addPostRequest(URIContant.VIDEO_LIST, new TypeToken<DataBean<NewsList>>() {
//                }.getType(), parmsMap, httpListener);
//            } else {
//                // 请求新闻列表接口
//                addPostRequest(URIContant.NEWSLIST, new TypeToken<DataBean<NewsList>>() {
//                }.getType(), parmsMap, httpListener);
//            }
//        } else {
//            //加载更多有缓存
//            if (TextUtils.equals(mChannelId, "9")) {
//                addPostCacheRequest(URIContant.VIDEO_LIST, new TypeToken<DataBean<NewsList>>() {
//                }.getType(), parmsMap, httpListener);
//            } else {
//                addPostCacheRequest(URIContant.NEWSLIST, new TypeToken<DataBean<NewsList>>() {
//                }.getType(), parmsMap, httpListener);
//            }
//
//        }

    }

    private NewsEntity flushRankData(DataBean<NewsList> response) {
        NewsEntity gameRanking = null;
        //获取排行榜数据
        List<GameCenterEntity> gameCenterEntityList = response.getData().getRankList();
        if (gameCenterEntityList != null && gameCenterEntityList.size() > 0) {
            gameRanking = new NewsEntity();
            gameRanking.setArticleType(TypeConstant.GAME_RANKING);
        }


        return gameRanking;


    }

    /**
     * LoadViewd 方法
     *
     * @param code 传入对应的值
     * @param msg  提示的的文字
     */
    protected void setLoadView(int code, CharSequence msg) {
        switch (code) {
            case NO_NET://网络错误
            case DATAERROR://数据错误
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showErrorPage(msg);
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                            //更改 底部导航栏
                            if (mOnRefreshingListener != null) {
                                mOnRefreshingListener.onDataRefreshingEnd();
                            }
                        }
                    }, 800);
                }
                break;
            case LOADING://加载中
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showLoadPage(msg);
                }
                break;
            case LOADSUCES://加载成功
                if (dataList != null && dataList.size() > 0) {
                    mLoadView.showSuccess();
                } else {
                    mLoadView.showEmptyPage(LoadViewConfig.EMPTY_DEFAULT, "");
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                            //更改 底部导航栏
                            if (mOnRefreshingListener != null) {
                                mOnRefreshingListener.onDataRefreshingEnd();
                            }
                        }
                    }, 800);
                }
                break;
        }

//        if (msg != null && !"".equals(msg)) {
//            notify_view_text.setText(msg);
//            notify_view_text.setVisibility(View.VISIBLE);
//            new Handler().postDelayed(new Runnable() {
//
//                @Override
//                public void run() {
//                    notify_view_text.setVisibility(View.GONE);
//                }
//            }, 2000);
//        }
    }

    private Handler picHanfler;//自动轮播图片操作
    private Timer timer;//自动轮播计时
    private View picView;//头部轮播图
    private View chanleLayout;//原创频道栏目
//    private View newsTopFlushView;//顶部刷新布局

    /**
     * 添加头部数据
     *
     * @param picList
     * @param isRefresh
     */
    private void initHeadData(List<NewsEntity> picList, List<VideoEntity> videoList, boolean isRefresh) {
        if (mListView == null) {
            return;
        }
        if (isRefresh) {
            //如果是刷新则移除轮播图
            if (mListView.getRefreshableView().getHeaderViewsCount() > 1) {
                //添加之前先移除原有的头部
                if (picView != null) {
                    mListView.getRefreshableView().removeHeaderView(picView);
                }
                if (chanleLayout != null) {
                    mListView.getRefreshableView().removeHeaderView(chanleLayout);
                }
                picView = null;
            }
            return;
        }
        //添加轮播图
        if (picList != null && picList.size() != 0) {
            if (mListView.getRefreshableView().getHeaderViewsCount() > 1 && picView != null) {
                //添加之前先移除原有的头部
                mListView.getRefreshableView().removeHeaderView(picView);
            }
            List<NewsEntity> picsList = picList;
            picView = LayoutInflater.from(getActivity()).inflate(
                    R.layout.layout_newslist_head1, null);
            //如果轮播图集合不为null
            ArrayList<ImageView> bigImgs = new ArrayList<ImageView>();
            TextView title = (TextView) picView.findViewById(android.R.id.text1);
            ViewGroup iconsView = (ViewGroup) picView.findViewById(android.R.id.widget_frame);
            final PairViewPager picViewPager = (PairViewPager) picView.findViewById(R.id.head_vp);
            picViewPager.setOffscreenPageLimit(picsList.size() + 2);
            for (int i = 0; i < picsList.size(); i++) {
                NewsEntity pic = picsList.get(i);
                if (pic == null) {
                    continue;
                }
                //在第一个位置加入最后一张图片
                if (i == 0 && picsList.get(picsList.size() - 1) != null && picsList.size() > 1) {
                    NewsEntity lastnews = picsList.get(picsList.size() - 1);
                    if (lastnews.getArticleThumb() != null && lastnews.getArticleThumb().length > 0) {
                        CustomImageView imageView = new CustomImageView(activity);
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        imageView.setLayoutParams(params);
                        imageView.setTag(picsList.get(picsList.size() - 1));
                        LoadImageUtils.getInstance().loadImageInstance(imageView, lastnews.getArticleThumb()[0]);
                        bigImgs.add(imageView);
                    }
                }
                if (pic.getArticleThumb() != null && pic.getArticleThumb().length > 0) {
                    CustomImageView imageView = new CustomImageView(activity);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    imageView.setLayoutParams(params);
                    imageView.setTag(pic);
                    LoadImageUtils.getInstance().loadImageInstance(imageView, pic.getArticleThumb()[0]);
                    bigImgs.add(imageView);
                    ImageView yuandian = new ImageView(activity);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewSizeUtils.dp2px(activity, 7), ViewSizeUtils.dp2px(activity, 5));
                    yuandian.setLayoutParams(layoutParams);
                    yuandian.setImageResource(R.drawable.news_list_head_yuandian_selector);
                    iconsView.addView(yuandian);
                }
                //在最后位置加入第一张图片
                if (i == (picsList.size() - 1) && picsList.get(0) != null && picsList.size() > 1) {
                    if (picsList.get(0).getArticleThumb() != null && picsList.get(0).getArticleThumb().length > 0) {
                        CustomImageView imageView1 = new CustomImageView(activity);
                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        imageView1.setLayoutParams(params);
                        imageView1.setTag(picsList.get(0));
                        LoadImageUtils.getInstance().loadImageInstance(imageView1, picsList.get(0).getArticleThumb()[0]);
                        bigImgs.add(imageView1);
                    }
                }

            }
            //如果只有一张图片则隐藏圆点
            if (iconsView.getChildCount() <= 1) {
                iconsView.setVisibility(View.GONE);
            }
            final NewsPicPagerAdapter adapter = new NewsPicPagerAdapter(bigImgs, iconsView, picsList, title, activity, picViewPager);
            picViewPager.setAdapter(adapter);
            picViewPager.setCurrentItem(1);
            picViewPager.setOnPageChangeListener(adapter);
            if (picsList.get(0) != null) {
                title.setText(picsList.get(0).getArticleTitle());
            }
            if (iconsView.getChildAt(0) != null) {
                (iconsView.getChildAt(0)).setSelected(true);
//                (iconsView.getChildAt(0)).setLayoutParams(new LinearLayout.LayoutParams(ViewSizeUtils.dp2px(activity, 8), ViewSizeUtils.dp2px(activity, 6)));
            }
            ViewSizeUtils.changeScreenW_H(picViewPager, 0.4f);

            if (iconsView.getChildCount() > 1) {
                //轮播图自动滚动
                picHanfler = new Handler() {
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case 0:
                                if (picViewPager == null) {
                                    return;
                                } else if (picViewPager.getCurrentItem() == adapter.getCount() - 2) {
                                    picViewPager.setCurrentItem(1);
                                } else {
                                    picViewPager.setCurrentItem(picViewPager.getCurrentItem() + 1);
                                }
                                break;
                        }
                    }
                };
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                timer = new Timer();
                timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        picHanfler.sendEmptyMessage(0);
                    }
                }, 5000, 5000);
            }
            mListView.getRefreshableView().addHeaderView(picView);
        }


        //添加视频频道 只添加一次
        if (videoList != null && videoList.size() >= 2 && chanleLayout == null) {
            chanleLayout = LayoutInflater.from(getActivity()).inflate(
                    R.layout.layout_news_video, null);
            CustomImageView customImageView = (CustomImageView) chanleLayout.findViewById(R.id.first_image);
            final TextView title = (TextView) chanleLayout.findViewById(R.id.first_title);
            TextView lable = (TextView) chanleLayout.findViewById(R.id.fist_channel);
            TextView qishu = (TextView) chanleLayout.findViewById(R.id.fist_qishu);
            final VideoEntity newsEntity = videoList.get(0);
            if (newsEntity.getArticleThumb() != null && newsEntity.getArticleThumb().length > 0) {
                LoadImageUtils.getInstance().loadImage(customImageView, newsEntity.getArticleThumb()[0]);
            }
            title.setText(newsEntity.getArticleTitle());
            lable.setText(newsEntity.getClickNum());
            qishu.setText(newsEntity.getCommentNum());

            chanleLayout.findViewById(R.id.first_layout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(activity, VideoDetailActivity.class);
                    intent.putExtra(Config.Extra.PARAMETER1, newsEntity.getArticleId());
                    intent.putExtra(Config.Extra.PARAMETER2, TypeConstant.SOURCETYPE_NORMAL);
                    activity.startActivity(intent);
                    StatService.onEvent(AppApplication.getInstance(), "067", "推荐列表顶部视频点击", 1);
                }
            });
            customImageView = (CustomImageView) chanleLayout.findViewById(R.id.second_image);
            final TextView title1 = (TextView) chanleLayout.findViewById(R.id.second_title);
            lable = (TextView) chanleLayout.findViewById(R.id.second_channel);
            qishu = (TextView) chanleLayout.findViewById(R.id.second_qishu);
            final VideoEntity newsEntity1 = videoList.get(1);
            if (newsEntity1.getArticleThumb() != null && newsEntity1.getArticleThumb().length > 0) {
                LoadImageUtils.getInstance().loadImage(customImageView, newsEntity1.getArticleThumb()[0]);
            }
            title1.setText(newsEntity1.getArticleTitle());
            lable.setText(newsEntity1.getClickNum());
            qishu.setText(newsEntity1.getCommentNum());
            chanleLayout.findViewById(R.id.second_layout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(activity, VideoDetailActivity.class);
                    intent.putExtra(Config.Extra.PARAMETER1, newsEntity1.getArticleId());
                    intent.putExtra(Config.Extra.PARAMETER2, TypeConstant.SOURCETYPE_NORMAL);
                    activity.startActivity(intent);
                    StatService.onEvent(AppApplication.getInstance(), "067", "推荐列表推荐视频点击", 1);
                }
            });
            mListView.getRefreshableView().addHeaderView(chanleLayout);
        }


    }

    /**
     * 数据去重
     *
     * @param list
     * @param calculateTop 计算置顶
     */
    private void dataRevisited(List<NewsEntity> list, boolean calculateTop) {
        if (list == null || list.size() == 0) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            if (i >= list.size()) {
                break;
            }
            NewsEntity ne = list.get(i);
            if (ne == null) {
                continue;
            }
            //如果是视频稿子 则进行数据匹配
            if (TextUtils.equals(ne.getArticleType(), TypeConstant.VIDEO_NORMAL)
                    || TextUtils.equals(ne.getArticleType(), TypeConstant.VIDEO_ORIGINAL)) {
                if (!TextUtils.equals(ne.getUrlStatus(), TypeConstant.NEWS_VIDEO_TYPE1)
                        && !TextUtils.equals(ne.getUrlStatus(), TypeConstant.NEWS_VIDEO_TYPE2)
                        && !TextUtils.equals(ne.getUrlStatus(), TypeConstant.NEWS_VIDEO_TYPE3)) {
                    list.remove(i);
                    i--;
                    continue;
                } else if (TextUtils.isEmpty(ne.getVideoUrl()) && TextUtils.isEmpty(ne.getVideoCurl())) {
                    //如果播放地址都为空则移除
                    list.remove(i);
                    i--;
                    continue;
                }
            }

            //删除没有匹配上的文章类型
            if (TextUtils.isEmpty(TypeConstant.getNewsTypeName(ne.getArticleType()))) {
                list.remove(i);
                i--;
                continue;
            }
            //如果计算置顶下标则记录置顶稿子下标
            if (calculateTop && TypeConstant.NEWS_ATTR_TOP.equals(ne.getArticleAttr())
                    && !TypeConstant.NEWS_TOPIC.equals(ne.getArticleType())) {
                // 如果是置顶属性 而又不是专题才记录置顶属性
                topIndex = i;
            }
            //开始去重计算
            if (listHasp.get(ne.getArticleId()) == null) {
                listHasp.put(ne.getArticleId(), ne.getArticleId());
            } else {
                list.remove(i);
                i--;
            }
        }
    }

    /**
     * 干扰数据添加广告
     *
     * @param list
     */
    private void insertAd(List<NewsEntity> list) {
        if (adList == null || adList.size() == 0) {
            return;
        }
        int size;
        if (dataList == null) {
            size = 0;
        } else {
            size = dataList.size();
        }
        AdConfig.insertAd(list, adList, size, circleNum, circleNativeAd);
    }

    /**
     * 干扰数据添加广告
     *
     * @param list
     */
    private void insertFlushAd(List<NewsEntity> list, List<NativeAd> adList) {
        AdConfig.insertAd(list, adList, mFlushCount);
    }

    /**
     * 干扰数据指定位置添加文章
     *
     * @param list
     */
    private void insertPositionNews(List<NewsEntity> list, List<NewsEntity> currentList) {
        if (list == null || list.size() == 0 || currentList == null || currentList.size() == 0) {
            return;
        }
        int sizeCount;
        if (dataList == null) {
            sizeCount = 0;
        } else {
            sizeCount = dataList.size();
        }
        int listsize = currentList.size();
        int listItem;
        for (int i = 0; i < listsize; i++) {
            listItem = i + sizeCount + 1;
            if (listItem <= list.get(list.size() - 1).getAdPosition()) {
                for (int j = 0; j < list.size(); j++) {
                    if (listItem == list.get(j).getAdPosition()) {
                        //如果位置匹配则添加
                        NewsEntity item = list.get(j);
                        currentList.add(i, item);
                        listsize++;
                        break;
                    }
                }

            } else {
                //如果当前索引位置已经超出了集合的最大所索引则直接跳出
                break;
            }
        }
    }

    /**
     * 重写下拉刷新
     *
     * @param refreshView
     */
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        this.mMark = 0;
        super.onPullDownToRefresh(refreshView);
        StatService.onEvent(activity, "066", "推荐列表下拉", 1);//统计事件的点击次数
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        this.mMark = 0;
        super.onPullUpToRefresh(refreshView);
        StatService.onEvent(activity, "066", "推荐列表上拉", 1);//统计事件的点击次数
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //因为有头部
        if (mListView.getRefreshableView().getHeaderViewsCount() > 0) {
            position = position - mListView.getRefreshableView().getHeaderViewsCount();
        }
        //防止越界
        if (position >= dataList.size()) {
            position = dataList.size() - 1;
        } else if (position < 0) {
            position = 0;
        }
        final NewsEntity news = dataList.get(position);
        if (news == null) return;
        if (!StringUtils.isEmpty(news.getArticleTitle())) {
            switch (news.getArticleType()) {
                case TypeConstant.NEWS_NORMAL:
                case TypeConstant.PIC_NORMAL:
                case TypeConstant.NEWS_WEB:
                    if ("推荐".equals(mChannelName)) {
                        MobclickAgentUtils.event(UmEventId.articlelist_click, UmEventId.INSTANCE.getRecommend());
                    } else if ("热点".equals(mChannelName)) {
                        MobclickAgentUtils.event(UmEventId.articlelist_click, UmEventId.INSTANCE.getHot());
                    }
                    StatService.onEvent(activity, "055", "信息流_文章", 1);// 统计的点击的次数
                    break;
                case TypeConstant.VIDEO_ORIGINAL:
                case TypeConstant.VIDEO_NORMAL:
                    if ("推荐".equals(mChannelName)) {
                        MobclickAgentUtils.event(UmEventId.videolist_click, UmEventId.INSTANCE.getRecommend());
                    } else if ("热点".equals(mChannelName)) {
                        MobclickAgentUtils.event(UmEventId.videolist_click, UmEventId.INSTANCE.getHot());
                    }
                    StatService.onEvent(activity, "055", "信息流_视频", 1);// 统计的点击的次数
                case TypeConstant.GAME_VIDEO:
                case TypeConstant.GAME_IMAGE:
                case TypeConstant.GAME_RAIDERS_TEXT:
                case TypeConstant.GAME_RAIDERS_VIDEO:
                    if ("推荐".equals(mChannelName)) {
                        MobclickAgentUtils.event(UmEventId.game_click, UmEventId.INSTANCE.getGame());
                    }
                    break;
                default:
                    break;
            }
        }

        if (!TypeConstant.openTypeDetail(news, activity, TypeConstant.SOURCETYPE_NORMAL)) {
            if (TextUtils.equals(news.getArticleType(), TypeConstant.FLUSH)) {
                flushData();
                StatService.onEvent(activity, "032", mChannelName, 1);// 统计的点击
                return;
            }
        }

        //添加已读文章id
        TextView textView = (TextView) view.findViewById(R.id.item_public_title);
        if (textView != null) {
            textView.setEnabled(false);
        }
        //添加已读新闻
        NewsAdapter.addReadList(news.getArticleId());
        SaveHistoryRunnable saveHistoryRunnable = new SaveHistoryRunnable(news);
        Executors.newFixedThreadPool(1).execute(saveHistoryRunnable);
    }

    private static class SaveHistoryRunnable implements Runnable {
        private NewsEntity news;

        public SaveHistoryRunnable(NewsEntity news) {
            this.news = news;
        }

        @Override
        public void run() {
            NewsDBUtil.getInstance().addHistoryData(news.getArticleId(), GsonUtils.getInstance().toJson(news));
        }
    }

    @Override
    public void startActivity(Intent intent) {
        if (activity != null) {
            activity.startActivity(intent);
        } else {
            super.startActivity(intent);
        }
    }

    @Override
    public void onClick(View view) {
        if (view == null) {
            return;
        }
        super.onClick(view);
        if (view.getId() == R.id.search) {
            //跳转搜索
            Intent intent = new Intent(activity, SearchActivity.class);
            startActivity(intent);
        }
//        else if(view.getId() == R.id.news_click_flush){
//
//            if(mListView != null && newsTopFlushView != null){
//                //标识已经被移除
//                newsTopFlushView.setTag(false);
//                //标识下次刷新不再添加
//                newsTopFlushView.setTag(R.id.tag_first,true);
//                mListView.getRefreshableView().removeHeaderView(newsTopFlushView);
//            }
//            changeData(true);
//        }

    }


    /**
     * 返回当前页面的list集合
     *
     * @return
     */
    public List getDataList() {
        return this.dataList;
    }

    /**
     * 搜索框的点击
     *
     * @param v
     */
    @Override
    public void onExtraHeaderClick(View v) {
        startActivity(new Intent(activity, SearchActivity.class));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void setOnRefreshingListener(MainActivity.OnRefreshingListener mOnRefreshingListener) {

        this.mOnRefreshingListener = mOnRefreshingListener;
    }

}
